package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.BolsaCheque;
import ar.republicagroup.gestion.entities.Cliente;
import ar.republicagroup.gestion.services.BolsaChequeServices;
import ar.republicagroup.gestion.services.ClienteServices;
import ar.republicagroup.gestion.util.SpringUtils;
import gk.jfilter.JFilter;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import ar.republicagroup.gestion.util.TableColumnAdjuster;
import ar.republicagroup.gestion.util.messages.UIMessages;
import java.awt.HeadlessException;
import java.awt.print.PrinterException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import org.apache.log4j.Logger;


public class frmCliente extends javax.swing.JFrame {

    ClienteServices clienteServices = (ClienteServices)SpringUtils.getBean("clienteServices");
    BolsaChequeServices bolsaChequeServices = (BolsaChequeServices)SpringUtils.getBean("bolsaChequeServices");
    
    private static List<Cliente> clienteList = new ArrayList<>();
    private static Logger log = Logger.getLogger(frmCliente.class);

    
    public frmCliente() {
        initComponents();
        cargarDatos();
        this.setIconImage(new ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/moneybox.png")).getImage());
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelContenedor = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCliente = new javax.swing.JTable();
        panelCrud = new javax.swing.JPanel();
        btnEliminar = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnNuevacuenta = new javax.swing.JButton();
        txtBusqueda = new javax.swing.JTextField();
        btnActualizar = new javax.swing.JButton();
        btnImprimirClientes = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...: Gestión de Clientes :..");
        setResizable(false);

        tblCliente.setAutoCreateRowSorter(true);
        tblCliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "Teléfono", "Celular", "Nextel", "Dirección", "Email", "CAP", "VC", "Depósito"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblCliente.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
        tblCliente.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tblCliente);

        panelCrud.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione un cliente"));
        panelCrud.setToolTipText("");

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/delete.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/edit.png"))); // NOI18N
        btnModificar.setText("Modificar");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelCrudLayout = new javax.swing.GroupLayout(panelCrud);
        panelCrud.setLayout(panelCrudLayout);
        panelCrudLayout.setHorizontalGroup(
            panelCrudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelCrudLayout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(btnModificar)
                .addGap(18, 18, 18)
                .addComponent(btnEliminar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelCrudLayout.setVerticalGroup(
            panelCrudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelCrudLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelCrudLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnModificar)
                    .addComponent(btnEliminar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnNuevacuenta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/add.png"))); // NOI18N
        btnNuevacuenta.setText("Nuevo cliente");
        btnNuevacuenta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevacuentaActionPerformed(evt);
            }
        });

        txtBusqueda.setFont(new java.awt.Font("Tahoma", 2, 12)); // NOI18N
        txtBusqueda.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBusquedaKeyReleased(evt);
            }
        });

        btnActualizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/update.png"))); // NOI18N
        btnActualizar.setText("Actualizar");
        btnActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarActionPerformed(evt);
            }
        });

        btnImprimirClientes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/printer.png"))); // NOI18N
        btnImprimirClientes.setText("Imprimir");
        btnImprimirClientes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirClientesActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelContenedorLayout = new javax.swing.GroupLayout(panelContenedor);
        panelContenedor.setLayout(panelContenedorLayout);
        panelContenedorLayout.setHorizontalGroup(
            panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelContenedorLayout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(panelContenedorLayout.createSequentialGroup()
                        .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnNuevacuenta)
                        .addGap(18, 18, 18)
                        .addComponent(btnActualizar))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 908, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(panelContenedorLayout.createSequentialGroup()
                        .addComponent(panelCrud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnImprimirClientes)))
                .addContainerGap(29, Short.MAX_VALUE))
        );
        panelContenedorLayout.setVerticalGroup(
            panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelContenedorLayout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnNuevacuenta)
                    .addComponent(btnActualizar))
                .addGap(28, 28, 28)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelContenedorLayout.createSequentialGroup()
                        .addComponent(panelCrud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelContenedorLayout.createSequentialGroup()
                        .addComponent(btnImprimirClientes)
                        .addGap(47, 47, 47))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelContenedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelContenedor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cargarDatos(){
        clienteList = clienteServices.findEntities();
        cargarTablaCliente(clienteList);
        reiniciarTextoDeBusqueda();
    }

    public static List<Cliente> getClienteList() {
        return clienteList;
    }

    public static void setClienteList(List<Cliente> clienteList) {
        frmCliente.clienteList.clear();
        frmCliente.clienteList = clienteList;
    }
    
    
    
    public static void cargarTablaCliente(List<Cliente> listado){
        try{
            DefaultTableModel model = (DefaultTableModel) tblCliente.getModel();
            model.fireTableDataChanged();
            model.getDataVector().clear();
            for(Cliente cliente : listado){
               model.addRow(new Object[]{cliente,cliente.getTelefono(),cliente.getCelular(),cliente.getNextel(),cliente.getDireccion(),cliente.getEmail(),cliente.getComisionBa(),cliente.getComisionInterior(),cliente.getComisionDeposito() });
            }
        
            TableColumnAdjuster tca = new TableColumnAdjuster(tblCliente);
            tca.adjustColumns();
            tblCliente.setModel(model);
            tblCliente.repaint();
        }catch(Exception ex){
           log.error(ex.getMessage());
        }
        
        
        
        }    

    private void btnNuevacuentaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevacuentaActionPerformed
          modalPanelAddCliente modalPanelAdd = new modalPanelAddCliente(this, true);
          modalPanelAdd.setLocationRelativeTo(this);
          modalPanelAdd.setVisible(true);
    }//GEN-LAST:event_btnNuevacuentaActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        if(tblCliente.getSelectedRow() != -1){
        DefaultTableModel model = (DefaultTableModel)tblCliente.getModel();
       /* OBTENEMOS LOS PARAMS PARA ENVIAR AL PANEL DE EDIT*/
        Cliente cliente           =  (Cliente)model.getValueAt(tblCliente.convertRowIndexToModel(tblCliente.getSelectedRow()),0);
        /* PRIMERO VALIDAMOS QUE EL CLIENTE NO TENGA REGISTRADA BOLSAS DE CHEQUE EL DIA DE HOY */
        List<BolsaCheque> chequesDelCliente = bolsaChequeServices.getBolsaChequeByFilters(cliente, new Date(), new Date(), null, false, null); 
        if(chequesDelCliente.isEmpty()){
            modalPanelEditCliente modalPanelEdit = new modalPanelEditCliente(this, true);
            modalPanelEdit.setId_cliente(cliente.getId());
            modalPanelEdit.setLocationRelativeTo(this);
            modalPanelEdit.setVisible(true);
        } else{
            JOptionPane.showMessageDialog(this, UIMessages.getInfoMessage("editClienteDisabled"),UIMessages.getInfoMessage("defaultInfoTitle"),JOptionPane.INFORMATION_MESSAGE);
            }
        }else {
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedCliente"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
        
        }
    }//GEN-LAST:event_btnModificarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
         
        if(tblCliente.getSelectedRow() != -1){
        DefaultTableModel model = (DefaultTableModel)tblCliente.getModel();
        /* OBTENEMOS LOS PARAMS PARA ENVIAR */
          Cliente cliente             = (Cliente)model.getValueAt(tblCliente.convertRowIndexToModel(tblCliente.getSelectedRow()), 0);
          int respuesta = JOptionPane.showConfirmDialog(this, "¿Desea eliminar el cliente "+cliente.getNombre()+" ?", UIMessages.getQuestionMessage("defaultQuestionTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

                if(respuesta == 0){
                    String mensaje =  clienteServices.delete(cliente.getId());
                    JOptionPane.showMessageDialog(this, mensaje, UIMessages.getInfoMessage("onCompleteDelete"), JOptionPane.INFORMATION_MESSAGE);
                }           
                refreshModelAfterSorting();
                cargarTablaCliente(clienteServices.findEntities());
        }else{
            JOptionPane.showMessageDialog(this, UIMessages.getErrorMessage("requiredSelectedCliente"), UIMessages.getErrorMessage("defaultErrorTitle"), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtBusquedaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusquedaKeyReleased
        txtBusqueda.setText(txtBusqueda.getText().toUpperCase());
        List<Cliente> coleccion = clienteList;
        JFilter<Cliente> filter = new JFilter(coleccion,Cliente.class);
        List<Cliente> result = filter.filter("{'nombre':{'$cts':'?1'}}", txtBusqueda.getText()).out(new ArrayList<Cliente>());
        cargarTablaCliente(result);
       
        if(txtBusqueda.getText().length() == 0){
            reiniciarTextoDeBusqueda();
            }
        
        
    }//GEN-LAST:event_txtBusquedaKeyReleased

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed
          refreshModelAfterSorting();
          clienteList  = clienteServices.findEntities();
          cargarTablaCliente(clienteList);
    }//GEN-LAST:event_btnActualizarActionPerformed

    private void btnImprimirClientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirClientesActionPerformed
        try {
            MessageFormat header = new MessageFormat(UIMessages.getInfoMessage("reporteClientes_title"),new Locale("es","ES"));
            boolean imprimio = tblCliente.print(JTable.PrintMode.FIT_WIDTH, header, null, true, null, true);
        
            if(imprimio){
                log.info("Imprimió reporte de Clientes...");
            }
        } catch (PrinterException ex) {
            log.error("Error al imprimir...");
            log.error(ex.getMessage());
        } catch (HeadlessException ex) {
            log.error(ex.getMessage());
            log.error("Sin encabezado ...");
        }
    }//GEN-LAST:event_btnImprimirClientesActionPerformed

    
    private void reiniciarTextoDeBusqueda(){
            txtBusqueda.setText("Ingrese nombre del cliente");
            txtBusqueda.requestFocus();
            txtBusqueda.selectAll();
    }
    
    public void refreshModelAfterSorting(){
            DefaultTableModel model = (DefaultTableModel) tblCliente.getModel();
            model.getDataVector().clear();
    }
   
    public static void main(String args[]) {
        
        

        
        
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmCliente().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    protected static javax.swing.JButton btnActualizar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnImprimirClientes;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton btnNuevacuenta;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelContenedor;
    private javax.swing.JPanel panelCrud;
    protected static javax.swing.JTable tblCliente;
    private javax.swing.JTextField txtBusqueda;
    // End of variables declaration//GEN-END:variables
}
